package com.tcs.start;

import com.tcs.channel.init.ServerChannelInit;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

public class StartUp {

    private final Logger logger = LoggerFactory.getLogger(StartUp.class);

    public  static void main(String [] args) {
        new StartUp().start();
    }

    public void start() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {
            serverBootstrap.group(group)
                    .channel(NioServerSocketChannel.class)
                    //保持连接数
                    .option(ChannelOption.SO_BACKLOG, 128)
                    //有数据立即发送
//                    .option(ChannelOption.TCP_NODELAY, true)
                    //保持连接
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .localAddress(new InetSocketAddress(5666))
                    .childHandler(new ServerChannelInit());
            ChannelFuture channelFuture = serverBootstrap.bind().sync();
            channelFuture.addListener(new GenericFutureListener() {

                @Override
                public void operationComplete(Future future) throws Exception {
                    if (future.isSuccess()) {
                        logger.info("成功!");
                    } else {
                        start();
                    }
                }
            });
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            logger.error("" , e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
